<?php

namespace App;

use Illuminate\Support\Facades\Redis;
use Illuminate\Database\Eloquent\Model;
use App\Library\PicCompress;
use Storage;
use DB;
use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Core\OssUtil;


class Carticle extends Model
{
    protected $table = "kl_circle_article";
    public $timestamps = false;

//是否置顶
    const TOP_YES = 1;
    const TOP_NO = 0;
    static $TopDisplay = [
        self::TOP_NO => '不置顶',
        self::TOP_YES => '置顶',
    ];
	
//是否删除
    const DEL_YES = 1;
    const DEL_NO = 0;
    static $DelDisplay = [
        self::DEL_NO => '已删除',
        self::DEL_YES => '未删除',
    ];
	
//是否加精
    const ISEXC_YES = 1;
    const ISEXC_NO = 0;
    static $IsexcDisplay = [
        self::ISEXC_NO => '未加精',
		self::ISEXC_YES => '加精',
    ];
	
//发布状态
    const PUSH_YES = 0;
    const PUSH_NO = 1;
    static $PushDisplay = [
        self::PUSH_YES => '已发布',
        self::PUSH_NO => '未发布',
    ];
	
    //图片还是视频
    const PORM_PIC = 1;
    const PORM_VIDEO = 2;
	

    /**
     * 新增
     * @param $request
     * @return array
     */
    static function zxartPublish($request)
    {

        DB::beginTransaction();

        //添加资讯
        $advice = new Carticle();
        $advice->user_id = $request->user_id;
        $advice->circle_id = $request->circle_id;
        $advice->content = $request->content;
        //$advice->is_top = $request->is_top;
        $advice->is_excellent = $request->is_excellent;
        
		if($request->is_excellent==1){
			$advice->excellent_time = date('Y-m-d H:i:s');
		}
        
		
		if($request->push_time){
			$advice->push_time = $request->push_time;
			$advice->create_time = $request->push_time;
			$advice->reply_time = date('Y-m-d H:i:s');
			$advice->push_flag = 1;
			$advice->is_del = 0;
		}else{
			$advice->create_time = date('Y-m-d H:i:s');
			$advice->reply_time = date('Y-m-d H:i:s');
			$advice->is_del = $request->is_del;
		}
		
			//上传的视频
		if ($request->has('file1')) {
			if (intval($request->porm) === self::PORM_VIDEO) {
				$extension = $request->file1->extension();
				if (!in_array($extension, ['rm', 'rmvb', 'mov', '3gp', 'mp4', 'flash', 'avi', 'wma', 'mid', 'm4v'])) {
					DB::rollBack();

					return ['status' => 2, 'message' => '视频格式不正确'];
				}
				$filename = self::OssVideo($request->file1);
				if ($filename['status'] !== 1) {
					DB::rollBack();

					return $filename;
				}
				$filename = $filename['message'];
				$video_path = Storage::disk('public')->put('/', $request->file1);
				//截取视频第一帧
				$pic_path = storage_path('app/public/test.png');
				$str = "ffmpeg -i " . storage_path('app/public/' . $video_path) . " -y -f mjpeg -ss 0 -t 1 " . $pic_path;
				system($str);//调用命令行
				//将截图上传到oss
				$pic = fopen($pic_path, 'r');
				Storage::disk('oss')->put($filename . '.png', $pic);
				//删除视频和截图
				Storage::disk('public')->delete($video_path);
				Storage::disk('public')->delete('test.png');
				$video_f = 'https://rans-7900.oss-cn-beijing.aliyuncs.com/' . $filename . '.png';
				//修改文章的video

				$advice->video_screenshots = $video_f;
				$advice->video = 'https://rans-7900.oss-cn-beijing.aliyuncs.com/' . $filename;
			}
		}
		
	    if(!$advice->save()) {
            DB::rollBack();
            return ['status' => 2, 'message' => '失败'];
        }
			
        if ($request->has('file1')) {
            //上传视频或者图片
            if (intval($request->porm) === self::PORM_PIC) {
                $picInsert = [];
                for ($i = 1; $i <= 9; $i++) {
                    $feild = 'file' . $i;
                    //如果有这张图片
                    if ($request->$feild) {
                        $extension = $request->$feild->extension();
                        if (!in_array($extension, ['png', 'jpg', 'jpeg', 'bmp', 'tiff', 'gif'])) {
                            DB::rollBack();

                            return ['status' => 2, 'message' => '图片格式不正确'];
                        }
                        //上传图片
                        $path = self::OssUpdate($request->$feild);
                        $path = 'https://rans-7900.oss-cn-beijing.aliyuncs.com/' . $path;
                        $picInsert[] = [
                            'circle_article_id' => $advice->id,
                            'pic_path' => $path,
							'create_time' => date('Y-m-d H:i:s'),
							'is_del' => 1
                        ];
                    }
                }
				
                //数据库添加数据
                $pic_insert = DB::table('kl_circle_pic')->insert($picInsert);
                if (!$pic_insert) {
                    DB::rollBack();

                    return ['status' => 2, 'message' => '图片上传失败'];
                }
            }
		}
		//Redis::set('circleArticleViewNumCount', $advice->id);
		//Redis::set('circleArticleLightNumCount', '0');
        DB::commit();

        return ['status' => 1, 'message' => '成功'];
    }
	
	
    static function OssUpdate($file)
    {
        return $file->store('/', 'oss');
    }

    /**
     * 修改
     * @param $advice
     * @param $request
     * @return array
     */
    static function zxartcirModify($advice, $request)
    {
        DB::beginTransaction();
		$art_id = $advice->id;
		//echo $art_id;
        //修改咨询
        $advice->user_id = $request->user_id;
        $advice->circle_id = $request->circle_id;
        $advice->content = $request->content;
       //$advice->is_top = $request->is_top;
        $advice->is_excellent = $request->is_excellent;

		if($request->is_excellent==1&&$advice->excellent_time==''){
			$advice->excellent_time = date('Y-m-d H:i:s');
		}		
        //$advice->is_del = $request->is_del;
		$advice->update_time = date('Y-m-d H:i:s');
		
		
        $picInsert = [];
        if ($request->has('pic0') || $request->has('pic1') || $request->has('pic2') || $request->has('pic3') || $request->has('pic4') || $request->has('pic5') || $request->has('pic6') || $request->has('pic7') || $request->has('pic8')) {
            for ($i = 0; $i < 9; $i++) {
                $filename = 'pic' . $i;
                if ($request->has($filename)) {
                    $extension = $request->$filename->extension();
                    if (!in_array($extension, ['png', 'jpg', 'jpeg', 'bmp', 'tiff', 'gif'])) {
                        DB::rollBack();

                        return ['status' => 2, 'message' => '图片格式不正确'];
                    }
                    //上传图片
                    $path = self::OssUpdate($request->$filename);
                    $path = 'https://rans-7900.oss-cn-beijing.aliyuncs.com/' . $path;
                    $picInsert[] = [
                        'circle_article_id' => $art_id,
                        'pic_path' => $path,
						'is_del' => 1,
						'create_time' => date('Y-m-d H:i:s'),
						
                    ];
                }
            }
            //数据库添加数据
            $pic_insert = DB::table('kl_circle_pic')->insert($picInsert);
            if (!$pic_insert) {
                DB::rollBack();

                return ['status' => 2, 'message' => '图片上传失败'];
            }
            if (DB::table('kl_circle_pic')->where('circle_article_id', $art_id)->count() > 9) {
                DB::rollBack();

                return ['status' => 2, 'message' => '图片上传失败'];
            }
        }


        if ($request->has('video')) {//上传的视频
            $extension = $request->video->extension();
            if (!in_array($extension, ['rm', 'rmvb', 'mov', '3gp', 'mp4', 'flash', 'avi', 'wma', 'mid'])) {
                DB::rollBack();

                return ['status' => 2, 'message' => '视频格式不正确'];
            }
            $filename = self::OssVideo($request->video);
            if ($filename['status'] !== 1) {
                DB::rollBack();

                return $filename;
            }
            $filename = $filename['message'];
            $video_path = Storage::disk('public')->put('/', $request->video);
            //截取视频第一帧
            $pic_path = storage_path('app/public/test.png');
            $str = "ffmpeg -i " . storage_path('app/public/' . $video_path) . " -y -f mjpeg -ss 0 -t 1 " . $pic_path;
            system($str);//调用命令行
            //将截图上传到oss
            $pic = fopen($pic_path, 'r');
            Storage::disk('oss')->put($filename . '.png', $pic);
            //删除视频和截图
            Storage::disk('public')->delete($video_path);
            Storage::disk('public')->delete('test.png');
            $video_f = 'https://rans-7900.oss-cn-beijing.aliyuncs.com/' . $filename . '.png';
            //修改文章的video
            $video = DB::table('kl_circle_article')->where('id', $art_id)->update([
                $advice->video_screenshots = $video_f,
                $advice->video = 'https://rans-7900.oss-cn-beijing.aliyuncs.com/' . $filename
            ]);
            if (!$video) {
                DB::rollBack();

                return ['status' => 2, 'message' => '视频上传失败'];
            }
        }
		
		
        if (!$advice->save()) {
            DB::rollBack();

            return ['status' => 2, 'message' => '失败'];
        }

        DB::commit();

        return ['status' => 1, 'message' => '成功'];
    }
	
    static function Cdelect($ids, $message = '')
    {
        DB::beginTransaction();

        //删除
        if (!DB::table('kl_circle_article')->where('id', $ids)->update(['is_del' => Carticle::DEL_NO])) {
            DB::rollBack();

            return ['status' => 2, 'message' => '删除失败'];
        }
        $times = 1;
        $user_ids = [Carticle::where('id', $ids)->value('user_id')];

        //添加behavior_log
        $behavior_log = BehaviorLog::UserBehaviorLog(47, 'del_post_times', $times);
        if ($behavior_log['status'] !== 1) {
            DB::rollBack();

            return $behavior_log;
        }

        //系统消息
        if ($message) {
            foreach ($user_ids as $user_id) {
                //添加系统消息
                $re = Curl::PushOneMessage($user_id, $message);
                if ($re['status'] !== 1) {
                    DB::rollBack();

                    return $re;
                }
            }
        }

        DB::commit();

        return ['status' => 1, 'message' => '成功'];
    }
	
    /**
     * 分片上传视频
     * @param $uploadFile
     * @return array
     */
    static function OssVideo($uploadFile)
    {
        $bucket = env('OSS_BUCKET');
        $pre = md5(basename($uploadFile) . time());
        $extension = $uploadFile->extension();
        $object = $pre . '.' . $extension;
        /**
         *  步骤1：初始化一个分片上传事件，获取uploadId。
         */
        try {
            $ossClient = new OssClient(env('OSS_ACCESSID'), env('OSS_ACCESSKEY'), env('OSS_ENDPOINT'));
            //返回uploadId，它是分片上传事件的唯一标识，您可以根据这个ID来发起相关的操作，如取消分片上传、查询分片上传等。
            $uploadId = $ossClient->initiateMultipartUpload($bucket, $object);
        } catch (OssException $e) {
            return ['status' => 2, 'message' => '视频上传失败'];
        }
        /*
         * 步骤2：上传分片。
         */
        $partSize = 10 * 1024 * 1024;
        $uploadFileSize = filesize($uploadFile);
        $pieces = $ossClient->generateMultiuploadParts($uploadFileSize, $partSize);
        $responseUploadPart = array();
        $uploadPosition = 0;
        $isCheckMd5 = true;
        foreach ($pieces as $i => $piece) {
            $fromPos = $uploadPosition + (integer)$piece[$ossClient::OSS_SEEK_TO];
            $toPos = (integer)$piece[$ossClient::OSS_LENGTH] + $fromPos - 1;
            $upOptions = array(
                $ossClient::OSS_FILE_UPLOAD => $uploadFile,
                $ossClient::OSS_PART_NUM => ($i + 1),
                $ossClient::OSS_SEEK_TO => $fromPos,
                $ossClient::OSS_LENGTH => $toPos - $fromPos + 1,
                $ossClient::OSS_CHECK_MD5 => $isCheckMd5,
            );
            // MD5校验。
            if ($isCheckMd5) {
                $contentMd5 = OssUtil::getMd5SumForFile($uploadFile, $fromPos, $toPos);
                $upOptions[$ossClient::OSS_CONTENT_MD5] = $contentMd5;
            }
            try {
                // 上传分片。
                $responseUploadPart[] = $ossClient->uploadPart($bucket, $object, $uploadId, $upOptions);
            } catch (OssException $e) {
                return ['status' => 2, 'message' => '视频分片上传失败'];
            }
        }
// $uploadParts是由每个分片的ETag和分片号（PartNumber）组成的数组。
        $uploadParts = array();
        foreach ($responseUploadPart as $i => $eTag) {
            $uploadParts[] = array(
                'PartNumber' => ($i + 1),
                'ETag' => $eTag,
            );
        }
        /**
         * 步骤3：完成上传。
         */
        try {
            // 在执行该操作时，需要提供所有有效的$uploadParts。OSS收到提交的$uploadParts后，会逐一验证每个分片的有效性。当所有的数据分片验证通过后，OSS将把这些分片组合成一个完整的文件。
            $ossClient->completeMultipartUpload($bucket, $object, $uploadId, $uploadParts);
        } catch (OssException $e) {
            return ['status' => 2, 'message' => '视频上传完成失败'];
        }
        return ['status' => 1, 'message' => $object];
    }


}
